/*
 * @Date: 2022-04-25 11:10:16
 * @LastEditors: jiangh1 1141429595@qq.com
 * @LastEditTime: 2022-10-13 09:52:01
 * @FilePath: \biblical-reptile\shengjinghouduan\controller\userController.js
 */
const User = require('../model/userModel')

class UserController {
    // 用户注册
    async register(ctx) {
        let { name, tel, password } = ctx.request.body
        const names = await User.getUser(name) //用户名是否重复
        const tels = await User.getTel(tel) //手机号是否重复

        if (tels.length > 0) {
            ctx.body = { type: 'warning', message: '该手机号已注册' }
        } else {
            if (names.length > 0) {
                ctx.body = { type: 'error', message: '用户名已存在' }
            } else {
                await User.insert(name, tel, password)
                ctx.body = { type: 'success', code: 0, message: '注册成功' }
            }
        }
    }

    // 登录
    async login(ctx) {
        // console.log(ctx);
        let name = ctx.request.body.name
        let password = ctx.request.body.password
        const res = (await User.getUser(name))[0]
        if (res) {
            if (res.password == password) {
                ctx.body = {
                    code: 0,
                    data: res,
                    message: '登录成功',
                    type: 'success'
                }
            } else {
                ctx.body = { type: 'error', message: '用户名或密码不正确' }
            }
        } else {
            ctx.body = { type: 'error', message: '用户名不存在' }
        }
    }

    //目录查询
    async menu(ctx) {
        console.log(ctx);
        const res = (await User.menu())
        const token = (await User.create_token())
        // console.log(res);
        if (res) {

            ctx.body = {
                code: 0,
                data: res,
                token: token,
                message: '数据请求成功',
                type: 'success'
            }

        } else {
            ctx.body = { type: 'error', message: '网络有误' }
        }

    }

    //二级目录查询
    async secondlevelmenu(ctx) {
        console.log(ctx);
        let menuId = ctx.request.body.menuId

        const res = (await User.secondlevelmenu(menuId))

        if (res) {

            ctx.body = {
                code: 0,
                data: res,
                message: '数据请求成功',
                type: 'success'
            }

        } else {
            ctx.body = { type: 'error', message: '网络有误' }
        }

    }

    // 文章查询
    async article(ctx) {
        console.log(ctx);
        let menuId = ctx.request.body.menuId
        let secondlevelmenuId = ctx.request.body.secondlevelmenuId

        const res = (await User.article(menuId, secondlevelmenuId))

        if (res) {

            ctx.body = {
                code: 0,
                data: res,
                message: '数据请求成功',
                type: 'success'
            }

        } else {
            ctx.body = { type: 'error', message: '网络有误' }
        }
    }
}
module.exports = new UserController()